<?php
/**
 * Created by PhpStorm.
 * User: Apache
 * Date: 2019/12/27
 * Time: 9:12
 */

namespace app\api\controller\finance;
use app\api\controller\common\ApiBase;
use Think\Db;

class Finance extends ApiBase
{
    protected $admin;
    protected $model;
    public function _initialize()
    {
        parent::_initialize();
        $this->admin = session('admin');
        $this->model = model('Finance');
    }

    /**
     * 添加财务
     */
    public function add(){
        $field = ['contract_id','pay_time','fee','currency'];
        $is = true;
        $data = [];
        foreach ($field as $v){
            if(empty(input($v))){
                $is = false;
                break;
            }
            if($v=='pay_time'){
                $data[$v] = strtotime(input($v));
            }else{
                $data[$v] = input($v);
            }
        }

        if(!$is){
            return json(['code'=>0,'msg'=>'请填写完整信息']);
        }
        $contractTotal=db('contract')->where(['id'=>input('contract_id'),'is_delete'=>0])->find();
        if(empty($contractTotal)){
            return json(['code'=>0,'msg'=>'合同展商有误']);
        }
        $sql="select sum(fee) as f_total from crm_finance where contract_id=".input('contract_id')." and is_delete=0 and status>1";
        $res=Db::query($sql);
        $total=$res[0]['f_total'];

        if(($total+input('fee'))>$contractTotal['money_total_ht']){
            return json(['code'=>0,'msg'=>'已超合同总金额,请查证后输入']);
        }
        $data['total_fee']=$total+input('fee');
        $data['create_time'] = time();
        $data['create_id'] = $this->admin['id'];
        $r = $this->model->insertData($data);
        if(!$r){
            return json(['code'=>0,'msg'=>'操作失败，请重试']);
        }

        return json(['code'=>1,'msg'=>'操作成功']);
    }

    public function index(){

        $page = $this->request->param('page');
        $page = max(1,intval($page));
        $pagesize =$this->request->param('pageSize')==""?10:$this->request->param('pageSize');
        $exhibition_id =$this->request->param('exhibition_id');
        $company =$this->request->param('company');//公司名称
        $fee =$this->request->param('fee');//付款金额
        $status =$this->request->param('status');//付款金额
        if(!$exhibition_id){
            return json(['code'=>0,'msg'=>'展会信息错误！']);
        }
        $tabName=$this->getTabName($exhibition_id);
        $param=" f.is_delete=0 ";
        if($company){
            $param.=" and f.contract_id in (select id from crm_contract where id_zs in (select id from crm_".$tabName." where company_name like '%$company%') and id_zhui=$exhibition_id and is_delete=0 and s_status=1)";
        }else{
            $param.=" and f.contract_id in (select id from crm_contract where id_zhui=$exhibition_id and is_delete=0 and s_status=1)";
        }
        if($status>0){
            $param.=" and f.status=$status";
        }
        if($fee>0){
            $param.=" and f.status=$status";
        }
        $sql="select f.*,c.company_name as name_zs,b.id contract_id,b.id_zhui,b.id_zs,b.ht_id,b.id_zs,b.money_total_ht";
        $sql.="  from crm_finance as f ";
        $sql.=" left join crm_contract as b on b.id=f.contract_id ";
        $sql.=" left join crm_".$tabName." as c on c.id=b.id_zs ";
        $sql.=" where 1=1 and $param";
        $sql.=" order by f.id desc";
        $total=Db::query($sql);
        $sql.=" limit ".($page-1)*$pagesize.",$pagesize";
        $list=Db::query($sql);
        return json(['code'=>1,'msg'=>'success','data'=>['list'=>$list,'count'=>count($total)]]);
    }

    public function detail(){
        $id = $this->request->param('id');
        $res=db('finance')->where(['id'=>$id])->find();
        if(!$res){
            return json(['code'=>0,'msg'=>'记录不存在']);
        }
        $contract=db('contract')->where(['id'=>$res['contract_id']])->find();
        $realname=db('admin')->where(['id'=>$res['create_id']])->find();
        $tabName=$this->getTabName($contract['id_zhui']);
        $company=db($tabName)->where(['id'=>$contract['id_zs']])->find();
        $res['company']=$company['company_name'];
        $res['realname']=$realname['realname'];
        return json(['code'=>1,'msg'=>'success','data'=>$res]);
    }

    /**
     * 审核
     */
    public function check(){
        Db::startTrans();
        try {
            $post = input('post.');
            $id = isset($post['id']) && $post['id'] != '' ? $post['id'] : 0;
            $company_id = isset($post['company_id']) && $post['company_id'] != '' ? $post['company_id'] : 0;
            $contract_id = isset($post['contract_id']) && $post['contract_id'] != '' ? $post['contract_id'] : 0;
            $contract = db('contract')->where(['id'=>$contract_id])->find();
            $status=-1;
            if(empty($contract)){
                return json(['code'=>0,'msg'=>'合同记录不存在']);
            }
            $tabName=$this->getTabName($contract['id_zhui']);
            $info=db('finance')->where(['id'=>$id])->find();
            if(empty($info)){
                return json(['code'=>0,'msg'=>'付款记录不存在']);
            }
            $exhi=db('exhibition')->where(['id'=>$contract['id_zhui']])->find();
            if(empty($exhi)){
                return json(['code'=>0,'msg'=>'展会记录错误']);
            }
            $finace = db($tabName)->where(['id'=>$company_id])->find();
            if(empty($finace)){
                return json(['code'=>0,'msg'=>'展商记录不存在']);
            }

            $contract_total=$contract['money_total_ht'];
            $money_total=db('finance')->where(['contract_id'=>$contract_id,'is_delete'=>0])->sum('fee');
            //总金额
            if(($contract_total-$money_total) < 0){
                return json(['code'=>0,'msg'=>'付款金额大于合同实际金额,请查证后重试']);
            }

            if(($contract_total-$money_total) == 0){
                $status=3;
            }

            if(($contract_total-$money_total) > 0){
                $status=2;
            }

            //更新付款记录

            $r = db('finance')->where(['id'=>$id])->update(['status'=>$status,'s_money'=>($contract_total-$money_total)]);
            if(false === $r){
                Db::rollback();
                return json(['code'=>'0','msg'=>'操作失败']);
            }
            //更新展商记录
            $followStatus = $status==2?5:6;
            $companyData['status']=$followStatus;
            $companyData['update_time']=time();
            #跟新展商状态，同时生成随机账号，随机密码
            if(!$finace['account'] || !$finace['pwd']){
                $rodom='0000'.$this->genUserNumber($contract['id_zhui'].$contract['id_zs']);
                $password=substr(time().'',-6);
                $companyData['account']=$rodom;
                $companyData['pwd']=$password;
            }
            $base = db($tabName)->where(['id'=>$company_id])->update($companyData);
            if(false === $base){
                Db::rollback();
                return json(['code'=>'0','msg'=>'操作失败']);
            }
            //更新老展商记录
            $oldRes=db('company_label')->where(['company_id'=>$finace['company_id1'],'exhibition_id'=>$exhi['id']])->find();
            if(!$oldRes){
                $oldData['company_id']=$finace['company_id1'];
                $oldData['member_id']=$finace['member_id'];
                $oldData['update_time']=time();
                $oldData['create_time']=date('Y');;
                $oldData['exhibition_name']=$exhi['title'];
                $oldData['exhibition_id']=$exhi['id'];
                $oldData['label_type']=1;
                $oldRes=db('company_label')->insert($oldData);
                if(false === $oldRes){
                    Db::rollback();
                    return json(['code'=>'0','msg'=>'操作失败']);
                }
            }
            Db::commit();
            return json(array('code' => '1', 'msg' => '成功'));
        } catch (\Exception $e) {
            Db::rollback();
            return json(array('code' => '0', 'msg' => $e->getMessage()));
        }
    }


    public function genUserNumber($prefix=''){
        $chars = md5(uniqid(mt_rand(), true));
        $uuid  = substr($chars,0,8);
        return $prefix . $uuid;
    }


    public function getTabName($exhibition_id){
        $result=db('exhibition')->where(['id'=>$exhibition_id])->find();
        $tabName="";
        if($result){
            $tabName=$result['create_tablename'];
        }else{
            return json(['code'=>0,'msg'=>'缺少关键字段','data'=>'']);
        }
        return $tabName;
    }

    /**
     * 合同列表
     */
    public function getList(){
        $page = $this->request->param('page');
        $page = isset($page) && $page != '' ? $page : 1;
        $pageSize = input('pageSize');
        $pageSize = isset($pageSize) && $pageSize != '' ? $pageSize : 10;
        $where['h.is_delete'] = 0;
        $where['h.s_status'] = 1;
        $page = max(1,intval($page));
        $list = db('contract')
            ->alias('h')
            ->field('h.*,e.id exhibition_id,e.title,a.realname')
            ->join('exhibition e','h.id_zhui=e.id','left')
            ->join('admin a','h.create_uid=a.id','left')
            ->where($where)
            ->order('id desc')
            ->select();
        $newList=[];
        if(!empty($list)){
            $ev['status']=array('gt',1);
            foreach ($list as &$v){
                $v['create_time'] = date('Y-m-d H:i:s',$v['create_time']);
                $ev['contract_id']=$v['id'];
                $ev['is_delete']=0;
                $ftotal=db('finance')->field('sum(fee) as f_total')->where($ev)->select();
                $ftto=empty($ftotal)?0:$ftotal[0]['f_total'];
                if(($v['money_total_ht']-$ftto)>0){
                    array_push($newList,$v);
                }
            }
            unset($v);
        }
        return json(['code'=>1,'msg'=>'success','data'=>['list'=>$newList]]);

    }


    /**
     * 删除财务
     */
    public function del(){
        $id = $this->request->param('id');
        $where = ['id'=>['in',$id],'is_delete'=>0];
        $r = $this->model->countWhere($where);
        if(empty($r)){
            return json(['code'=>0,'msg'=>'记录不存在，请核实']);
        }
        $r = $this->model->deleteWhere(['id'=>$id]);
        if(!$r){
            return json(['code'=>0,'msg'=>'操作失败，请重试']);
        }
        return json(['code'=>1,'msg'=>'操作成功']);
    }


    /**
     * 编辑财务
     */
    public function edit(){
        $id=$this->request->param('id');
        if(empty($id)){
            return json(['code'=>0,'msg'=>'缺少关键主键id']);
        }
        $field = ['contract_id','pay_time','fee','currency'];
        $is = true;
        $data = [];
        foreach ($field as $v){
            if(empty(input($v))){
                $is = false;
                break;
            }
            if($v=='pay_time'){
                $data[$v] = strtotime(input($v));
            }else{
                $data[$v] = input($v);
            }
        }

        if(!$is){
            return json(['code'=>0,'msg'=>'请填写完整信息']);
        }
        $contractTotal=db('contract')->where(['id'=>input('contract_id'),'is_delete'=>0])->find();
        if(empty($contractTotal)){
            return json(['code'=>0,'msg'=>'合同展商有误']);
        }
        $sql="select sum(fee) as f_total from crm_finance where contract_id=".input('contract_id')." and is_delete=0 and status>1";
        $res=Db::query($sql);
        $total=$res[0]['f_total'];
        if(($total+input('fee'))>$contractTotal['money_total_ht']){
            return json(['code'=>0,'msg'=>'已超合同总金额,请查证后输入']);
        }
        $data['total_fee']=$total+input('fee');
        $data['create_time'] = time();
        $data['create_id'] = $this->admin['id'];
        $where['id'] = $id;
        $r = $this->model->updateBywhere($data,$where);
        if(!$r){
            return json(['code'=>0,'msg'=>'操作失败，请重试']);
        }
        return json(['code'=>1,'msg'=>'操作成功']);
    }

    /**
     * 此处需要两个接口，主要用来权限区分
     * 领导退回财务提交
     */
    public function save(){
        $status = $this->request->param('status');
        $fText = $this->request->param('f_text');
        $id = $this->request->param('id');
        if(empty($id)){
            return json(['code'=>0,'msg'=>'缺少关键主键id']);
        }
        //$fType 为审核状态 4退回
        if($status == 4){
            if(empty($fText)){
                return json(['code'=>0,'msg'=>'请填写审核意见']);
            }else{
                $data['finance_text']=$fText;
            }
        }
        $data['status']=$status;
        $where['id'] = $id;
        $r = $this->model->updateBywhere($data,$where);
        if(!$r){
            return json(['code'=>0,'msg'=>'操作失败，请重试']);
        }
        return json(['code'=>1,'msg'=>'操作成功']);
    }

    /**
     * 业务员重新提交
     */
    public function againSave(){
        $status = $this->request->param('status');
        $id = $this->request->param('id');
        if(empty($id)){
            return json(['code'=>0,'msg'=>'缺少关键主键id']);
        }
        $data['status']=$status;
        $where['id'] = $id;
        $r = $this->model->updateBywhere($data,$where);
        if(!$r){
            return json(['code'=>0,'msg'=>'操作失败，请重试']);
        }
        return json(['code'=>1,'msg'=>'操作成功']);
    }
}